//
//  GKZYPostBarPublishViewController.m
//  GKZYAid
//
//  Created by lanou3g on 16/3/14.
//  Copyright © 2016年 GKZYAid. All rights reserved.
//

#import "GKZYPostBarPublishViewController.h"
#define CELLID @"cell_id"

@interface GKZYPostBarPublishViewController ()

@end

@implementation GKZYPostBarPublishViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.arrayCount = self.arrayImage.count - 1;
    [self addButtonSave];
    self.scrollV.contentSize = CGSizeMake(0, (self.arrayImage.count / 3 + 1) * [UIScreen mainScreen].bounds.size.width * 0.27 + [UIScreen mainScreen].bounds.size.width * 0.8);
    if (self.arrayImage.count > 9) {
        self.scrollV.contentOffset = CGPointMake(0, (int)(self.arrayImage.count - 1) / 3 * [UIScreen mainScreen].bounds.size.width * 0.25);
    }
}

- (NSMutableArray *)arrayImage
{
    if (!_arrayImage) {
        _arrayImage = [[NSMutableArray alloc] init];
    }
    return _arrayImage;
}


- (NSMutableArray *)arrayImageFile
{
    if (!_arrayImageFile) {
        _arrayImageFile = [[NSMutableArray alloc] init];
    }
    return _arrayImageFile;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addAllViews];
    [self addButtonSave];
    [self.arrayImage addObject:[UIImage imageNamed:@"addImage"]];
}

- (void)addAllViews;
{
    self.scrollV = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.scrollV.contentSize = CGSizeMake(0, 3000);
    self.scrollV.delegate = self;
    [self.view addSubview:self.scrollV];
    
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 0.05, self.view.frame.size.width * 0.05, self.view.frame.size.width * 0.9, self.view.frame.size.width * 0.3)];
    self.textView.layer.masksToBounds = YES;
    self.textView.layer.cornerRadius = 10;
    self.textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.textView.layer.borderWidth = 1.5f;
    self.textView.font = [UIFont systemFontOfSize:17.0f];
    [self.scrollV addSubview:self.textView];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.view.frame.size.width * 0.25, self.view.frame.size.width * 0.25);
    layout.sectionInset = UIEdgeInsetsMake(self.view.frame.size.width * 0.02, self.view.frame.size.width * 0.02, self.view.frame.size.width * 0.02, self.view.frame.size.width * 0.02);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 0.05, self.view.frame.size.width * 0.35, self.view.frame.size.width * 0.9, [UIScreen mainScreen].bounds.size.height * 5) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.scrollV addSubview:self.collectionView];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[GKZYPublishCollectionViewCell class] forCellWithReuseIdentifier:CELLID];
}

- (void)addButtonSave
{
    [self.buttonSave removeFromSuperview];
    self.buttonSave = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.buttonSave setTitle:@"发表" forState:(UIControlStateNormal)];
    self.buttonSave.frame = CGRectMake(self.view.frame.size.width * 0.05, self.view.frame.size.width * 0.4 + (self.arrayCount / 3 + 1) * self.view.frame.size.width * 0.28, self.view.frame.size.width * 0.9, self.view.frame.size.width * 0.15);
    self.buttonSave.tag = 110;
    self.buttonSave.backgroundColor = [UIColor orangeColor];
    [self.scrollV addSubview:self.buttonSave];
    [self.buttonSave addTarget:self action:@selector(buttonSaveAction:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)buttonSaveAction:(UIButton *)sender
{
    [self addActivityIndicatorView];
    [self.textView resignFirstResponder];
    
    PostBar *postBar = [PostBar object];
    postBar.arrayPublicationImage = [[NSMutableArray alloc] init];
    NSMutableArray *arrayPhotoFiles = [[NSMutableArray alloc] init];
    NSError *error;
    if (self.arrayImage.count > 1) {
        for (UIImage *photo in self.arrayImage) {
            HelperModifyUserIconSize *helper = [[HelperModifyUserIconSize alloc] init];
            UIImage *photoNew= [helper modifyUserHeaderPortraitSize:photo WithImageWidth:photo.size.width * 0.5 imageHeight:photo.size.height * 0.5];
            AVFile *photofile = [AVFile fileWithData:UIImageJPEGRepresentation(photoNew, 1.0f)];
            [photofile save:&error];
            if (error) {
                return;
            }
            [arrayPhotoFiles addObject:photofile];
        }
        postBar.arrayPublicationImage = arrayPhotoFiles;
    }
    
    postBar.strPublicationUserName = [AVUser currentUser].username;
    postBar.strPublicationrContent = self.textView.text;
    postBar.strCommentContent = @"";
    postBar.strCommentUserName = @"";
    postBar.strReplyUserName = @"";
    postBar.strReplyContent = @"";
    postBar.strPassivityReplyUserName = @"";
    postBar.arrayUserLike = [[NSMutableArray alloc] init];
    postBar.strPublicationID = [self generateID];
    [postBar save:&error];
    if (!error) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (NSString *)generateID
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:8 * 60 * 60];
    NSString *str = [NSString stringWithFormat:@"%@",date];
    NSString *year = [str substringWithRange:NSMakeRange(0, 4)];
    NSString *month = [str substringWithRange:NSMakeRange(5, 2)];
    NSString *day = [str substringWithRange:NSMakeRange(8, 2)];
    NSString *hour = [str substringWithRange:NSMakeRange(11, 2)];
    NSString *min = [str substringWithRange:NSMakeRange(14, 2)];
    NSString *sec = [str substringWithRange:NSMakeRange(17, 2)];
    NSInteger randomValue = arc4random() % (1000 - 100 + 1) + 1;
    NSString *strRan = [NSString stringWithFormat:@"%ld",randomValue];
    NSString *strId = [NSString stringWithFormat:@"%@%@%@%@%@%@%@",year,month,day,hour,min,sec,strRan];
    return strId;
}

- (void)addUploadWrongErrorAlertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"发表失败!" message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

//返回每个分组有多少个单元
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrayImage.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GKZYPublishCollectionViewCell *cellPublish = [collectionView dequeueReusableCellWithReuseIdentifier:CELLID forIndexPath:indexPath];
    cellPublish.imageV.image = self.arrayImage[indexPath.row];
    return cellPublish;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.arrayImage.count - 1) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *imageNew = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self.arrayImage insertObject:imageNew atIndex:self.arrayImage.count - 1];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.collectionView reloadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addActivityIndicatorView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [view setTag:108];
    [view setBackgroundColor:[UIColor blackColor]];
    [view setAlpha:0.5];
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [self.activityIndicator setCenter:view.center];
    [self.activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [view addSubview:self.activityIndicator];
    [self.activityIndicator startAnimating];
    [self.view addSubview:view];
}

- (void)removeActivityIndicatorView
{
    [self.activityIndicator stopAnimating];
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
